import { app, shell, BrowserWindow, ipcMain, session } from 'electron';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from '../../resources/icon.png?asset';
import { machineIdSync } from 'node-machine-id';
import './websocket';
import './crypto';
import { clientConfig } from './config';
import { initKeypair } from './crypto';
import './dispatcher';
import './message';

let mainWindow: BrowserWindow;

let isMinSize = false;

function createWindow(
  path: 'login' | 'index',
  token?: string,
  userId?: string,
  name?: string
): void {
  // 创建浏览器窗口
  mainWindow = new BrowserWindow({
    width:
      path === 'login'
        ? clientConfig.smallScreen.width
        : clientConfig.largeScreen.width,
    height:
      path === 'login'
        ? clientConfig.smallScreen.height
        : clientConfig.largeScreen.height,
    minWidth:
      path === 'login'
        ? clientConfig.smallScreen.width
        : clientConfig.largeScreen.width,
    minHeight:
      path === 'login'
        ? clientConfig.smallScreen.height
        : clientConfig.largeScreen.height,
    show: false,
    autoHideMenuBar: true,
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: clientConfig.preloadPath,
      sandbox: false,
      devTools: true
    }
  });

  mainWindow.on('ready-to-show', () => {
    mainWindow.show();
    // mainWindow.webContents.openDevTools();
    mainWindow.webContents.send('user-token', token);
    mainWindow.webContents.send('user-info', { userId: userId, name: name });
    mainWindow.webContents.send('user-machineId', machineIdSync());
    if (userId) {
      initKeypair(userId)
        .then(() => {
          mainWindow.webContents.send('key-init-status', true);
        })
        .catch((err) => {
          mainWindow.webContents.send('key-init-status', false);
          console.log('主进程-创建密钥对失败：', err);
        });
    }
  });

  mainWindow.on('minimize', () => {
    isMinSize = true;
  });

  mainWindow.on('restore', () => {
    isMinSize = false;
  });

  mainWindow.webContents.setWindowOpenHandler((details) => {
    shell.openExternal(details.url);
    return { action: 'deny' };
  });

  // 基于electron-vite cli的渲染器的热模块替换(HMR)
  // 开发时加载远程URL，或生产时加载本地html文件
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
  } else {
    mainWindow.loadFile(clientConfig.rootHtmlPath, {
      hash: path === 'login' ? '/login' : '/index'
    });
  }
}

ipcMain.on('login-success', (_, token, userId, name) => {
  mainWindow.close();
  createWindow('index', token, userId, name);
});

ipcMain.on('login-logout', () => {
  mainWindow.close();
  createWindow('login');
});

ipcMain.on('window-minimized', (event, _) => {
  event.sender.send('window-minimized', isMinSize);
});

// Electron完成初始化并准备创建浏览器窗口时，将调用此方法
// 有些API在这个事件发生后才能使用
app.whenReady().then(() => {
  // 添加自签名证书的支持
  session.defaultSession.setCertificateVerifyProc((request, callback) => {
    if (request.hostname === 'localhost') {
      callback(0);
    } else {
      callback(-2);
    }
  });

  // 为Windows设置应用程序用户模型ID
  electronApp.setAppUserModelId(clientConfig.appUserModelId);

  // 默认在开发环境下通过F12打开或关闭DevTools
  // 生产环境中忽略CommandOrControl + R
  // 参考https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window);
  });

  createWindow('login');

  app.on('activate', function () {
    // 在macOS上，当点击dock图标并且没有其他窗口打开时，通常会在app中重新创建一个窗口
    if (BrowserWindow.getAllWindows().length === 0) createWindow('login');
  });
});

// 当所有窗口都被关闭时退出，macOS除外。在macOS上，除非用户使用Cmd + Q显式退出，否则通常会保持应用程序及其菜单栏的活动状态
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});
